// pages/major/index.js
const {
  schoolList,
  schoolAdd,
  twoMajorList,
  majorPageList
} = require('../../../api/api')

const {
  checkLogin,
  filterObj
} = require('../../../utils/util')
const selectorRouteDatas = [{
    id: 0,
    title: "专业层级",
    key: "level1Name",
    type: 'radiobox',
    items: [{
        id: '',
        title: "不限",
        checked: true
      },
      {
        id: '本科',
        title: "本科",
      }, {
        id: '专科（高职）',
        title: "专科（高职）",
      }
    ],
  },
  {
    id: 1,
    title: "专业类型",
    key: "category",
    type: 'radiobox',
    items: [],
  },
  {
    id: 2,
    title: "专业排序",
    key: "orderBy",
    type: 'radiobox',
    items: [{
        id: 'hotDesc',
        title: "专业热度由高到底",
        checked: true
      }, {
        id: 'spCode',
        title: "专业代码排序",
      },
      {
        id: 'salaryDesc',
        title: "平均薪酬由高到低",
        icon:'/images/my/vip.png',
        width: '60rpx',
        height: '26rpx'
      },
      {
        id: 'boyDesc',
        title: "男生比例由高到低",
      },
      {
        id: 'girlDesc',
        title: "女生比例由高到底",
      },
    ],
  },
]

Page({

  /**
   * 页面的初始数据
   */
  data: {
    show:false,
    currentIndex: 0,
    list: [],
    currentRegion: {
      name: '全国',
      code: 0
    },
    selectedData: {
      category: 1, //查询专业一级
      categoryId: 16, //查询专业二级id
      orderBy: 'hotDesc',
      level1Name: '',
    },
    selectorDataList: selectorRouteDatas,
    categoryFilter: {
      id: 1,
      title: "专业类别",
      key: "category",
      type: 'other',
      items: []
    },
    showSelect: false,
    type: {
      name: '本科',
      id: 2,
    },
    pageNo: 1,
    loginVisible: true,
    pageSize: 20,
    filterRouteKey: "majorFilters",
    selectedMajorList: [],
    categoryList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // if (wx.getStorageSync('majorFilters')) {
    let selectedData = {
      category: 0, //查询专业一级
      categoryId: 0, //查询专业二级id
      orderBy: 'hotDesc',
      level1Name: '',
    }
    wx.setStorageSync('majorFilters', selectedData)
    wx.removeStorageSync('categoryItem')
    // }
    this.fetchCategory()
  },
  async fetchCategory() {
    const {level1Name} = wx.getStorageSync('majorFilters')
    const params = {
      level1Name
    }
    const {
      selectorDataList
    } = this.data
    const {
      result
    } = await twoMajorList(params)
    // const categoryList = result.map((item) => {
    //   const children = item.children.map((child) => {
    //     return {
    //       title: child.name,
    //       id: child.id
    //     }
    //   })
    //   children.unshift({
    //     id: 0,
    //     title: '不限'
    //   })
    //   return {
    //     id: item.id,
    //     title: item.name,
    //     children
    //   };
    // })
    // // selectorDataList[1].items=categoryList
    // categoryList.unshift({
    //   id: 0,
    //   title: '全部',
    //   children: [{
    //     id: 0,
    //     title: '不限'
    //   }]
    // })
    this.setData({
      categoryOldList:result,
    })
    this.getCategory()
  },
 getCategory(){
  // eduLevel_dictText
  let selectedData = wx.getStorageSync('majorFilters')
  let {categoryOldList,selectorDataList}=this.data
  // if(selectedData.level1Name){
  //   categoryOldList=categoryOldList.filter(e=>{
  //     return e.eduLevel_dictText==selectedData.level1Name
  //   })
  // }
    const categoryList = categoryOldList.map((item) => {
      const children = item.children.map((child) => {
        return {
          title: child.name,
          id: child.name
        }
      })
      children.unshift({
        id: 0,
        title: '不限'
      })
      return {
        id: item.name,
        title: item.name,
        children
      };
    })
    categoryList.unshift({
      id: 0,
      title: '全部',
      children: [{
        id: 0,
        title: '不限'
      }]
    })
    this.setData({
      categoryList,
    })
    if(this.data.selectedData.level1Name!==selectedData.level1Name){
        selectedData.category=0
        selectedData.categoryId=0
        selectorDataList[1].title='专业类别'
        wx.removeStorageSync('categoryItem')
    }
    wx.setStorageSync('majorFilters', selectedData)
    this.filterKeyFunc()
 },
  updateScore(){
    let selectedData = {
      category: 0, //查询专业一级
      categoryId: 0, //查询专业二级id
      orderBy: 'hotDesc',
      level1Name: '',
    }
    wx.setStorageSync('majorFilters', selectedData)
    wx.removeStorageSync('categoryItem')
    // }
    this.fetchCategory()
  },
  onShow: function () {
    checkLogin().then((res) => {
      if (!wx.getStorageSync('subjectInfo')) {
        this.setData({
          show: true
        })
      }
    })
  },
  // onShow: function () {
  //   checkLogin().then((res) => {
  //     this.filterKeyFunc()
  //   }).catch((e) => {
  //     this.setData({
  //       loginVisible: false,
  //       list: []
  //     })
  //   })
  // },
  //修改筛选条件--执行onloadFunc
  filterKeyFunc() {
    const selectedData = wx.getStorageSync('majorFilters')
    const categoryName = wx.getStorageSync('categoryItem').title || ''
    const {category,categoryId,level1Name,orderBy}=selectedData
    const {
      selectorDataList
    } = this.data
    selectorDataList.map((item) => {
      const c = item.items.filter((child) => {
        return child.id == selectedData[item.key]
      })
      // const isCategory = item.key == 'category'
      // item.title = isCategory ? (categoryName || item.title) : c.length > 0 ? c[0].title : item.title
      // c[0].title
       const isCategory = item.key == 'category'
        item.title = isCategory ? (categoryId && categoryId!=0?(categoryId  || item.title):category?(category || item.title):'专业类型') : item.key == 'level1Name' && !level1Name?'专业层级':item.key == 'orderBy' && orderBy=='hotDesc'?'专业排序':c.length > 0 ? c[0].title : item.title
        return item
    })
    this.setData({
      selectorDataList,
      selectedData
    })
    this.onLoadFunc()
  },

  async onSelectChangedRoute(e) {
    const {level1Name}=this.data.selectedData
    wx.setStorageSync('majorFilters', {
      ...e.detail
    });
    // console.log(e.detail)
    // this.filterKeyFunc()
    if(level1Name!==e.detail.level1Name){
      this.fetchCategory()
      return
    }
    this.getCategory()
    // this.setData({
    //   ...e.detail
    // });
  },
  onLoadFunc() {
    this.setData({
      pageNo: 1,
      list: []
    })
    this.getList()
  },
  async getList() {
    const {
      pageNo,
      pageSize,
      selectedData,
      filterRouteKey
    } = this.data
    const {categoryId,category,orderBy,level1Name} = wx.getStorageSync(filterRouteKey)
    console.log(categoryId)
    let level3Name=categoryId
    if(Array.isArray(categoryId)){
      level3Name=''
    }
    let params = {
      level1Name,
      level2Name:category,
      level3Name:level3Name,
      pageNo,
      pageSize,
      orderBy,
    }
    params=filterObj(params)
    console.log(params)
    const {
      result
    } = await majorPageList(params)
    // if (result.records.length == 0) {
    //   return
    // }
    this.setData({
      ['list[' + (pageNo - 1) + ']']: result.records,
      pageNo: pageNo + 1,
    })
  },
  changeIndex(e) {

  },
  onReachBottom() {
    const {
      list,
      pageSize
    } = this.data
    const count = list.length - 1
    if (list[count].length < pageSize) {
      return
    }
    this.getList()
  },

  goto(e) {
    const {
      url,
    } = e.currentTarget.dataset
    wx.navigateTo({
      url
    })
  },
  chooseCity() {
    wx.navigateTo({
      url: '/pages/list/index?type=school&category=city',
    })
  },
  getImageLogo() {
    return 'https://static-data.gaokao.cn/upload/logo/42.jpg'
  },
  chooseType() {
    this.setData({
      showSelect: true
    })
  },


  search() {
    // checkLogin().then((res) => {
      wx.navigateTo({
        url: '/pages/search/index?type=major',
      })
    // }).catch((e) => {
    //   this.setData({
    //     loginVisible: false,
    //     list: []
    //   })
    // })

  },
  // 院校收藏
  async collect(e) {
    const {
      id,
      index
    } = e.currentTarget.dataset
    if (this.data.list[index].isCollection) return
    const {
      result
    } = await schoolAdd(id)
    wx.showToast({
      title: '收藏成功',
      icon: 'none'
    })
    this.data.list[index].isCollection = true
    this.setData({
      list: this.data.list
    })
  },
  onShareAppMessage() {
    return {
      title: '专业查询',
      imageUrl: 'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/users/shareImg.jpg'
    }
  }
})
